class Solution:
    def validateBinaryTreeNodes(self, n: int, leftChild: list,
                                rightChild: list) -> bool:
        def dfs(node, leftChild, rightChild, visited):
            if node == -1:
                return True
            if node in visited:
                return False
            visited.add(node)
            return dfs(leftChild[node],
                       leftChild, rightChild, visited) and dfs(
                           rightChild[node], leftChild, rightChild, visited)

        nodes = set([i for i in range(n)])
        for i in range(n):
            if leftChild[i] in nodes:
                nodes.remove(leftChild[i])
            if rightChild[i] in nodes:
                nodes.remove(rightChild[i])
        if len(nodes) == 0:
            return False
        head = nodes.pop()
        visited = set()
        if dfs(head, leftChild, rightChild, visited):
            return len(visited) == n


if __name__ == "__main__":
    print(Solution().validateBinaryTreeNodes(4, [1, -1, 3, -1],
                                             [2, -1, -1, -1]))
